﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using Runda.CMS.Common.Entity;
using Runda.CMS.Bll;
using Runda.CMS.Common.Utility;
using System.Collections.Generic;
using Runda.CMS.Workflow;
using System.Text;
using Runda.CMS.Common.Exchange;

namespace Runda.CMS.Portal.ContractManage
{
    public partial class ContractAdd : WorkflowPage
    {
        public Guid ContractID
        {
            get
            {
                if (txtContractID.Value == string.Empty) return Guid.Empty;
                else return new Guid(txtContractID.Value);
            }
            set {
                txtContractID.Value = value.ToString(); 
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        { 
            if (!IsPostBack)
            {
                CheckTabPermission();

                listContractType.BindEnum(EnumeratorHelper.GetFieldTexts(typeof(Enumerator.ContractType)));

                List<SqlDbParameter> parms = new List<SqlDbParameter>();
                SqlDbParameter parm = new SqlDbParameter();
                parm.ColumnName = "Type";
                parm.ColumnType = DbType.Int32;
                parm.ParameterName = "@Type";
                parm.ParameterValue = System.Convert.ToInt32(ContractEnumerator.ContractParms.contractAttr);
                parm.QualificationType = SqlDbParameter.QualificationSymbol.Equal;
                parms.Add(parm);
                listContractAttribute.DataSource = new SysDictionaryBll().GetAll<SysDictionaryEntity>(parms);
                listContractAttribute.DataTextField = "Code";
                listContractAttribute.DataValueField = "ID";
                listContractAttribute.DataBind();
                if (Request.QueryString["ContractID"] != null)
                {
                    ContractID = new Guid(Request.QueryString["ContractID"]);
                    InitForm();

                    //LoadItem();
                }
                else
                {
                    lnkbtnSubmit.Enabled = false;
                    pnlChange.Visible = false;
                }
            }
        }

        private void InitForm()
        {
            CtrtContractEntity entity = new CtrtContractEntity();
            CtrtContractBll bll = new CtrtContractBll();

            if (ContractID != Guid.Empty)
            {
                entity = bll.Get<CtrtContractEntity>(ContractID);
                txtContractCode.Text = entity.ContractCode;             
                listContractAttribute.SelectedValue = entity.ContractAttribute.ToString();

                if (entity.ContractApplyDate != DateTime.MinValue)
                    txtContractApplyDate.SelectedDate = entity.ContractApplyDate;

                //if (entity.ContractEstimateSignDate != DateTime.MinValue)
                //    txtContractEstimateSignDate.SelectedDate = entity.ContractEstimateSignDate;
              
                listContractType.SelectedValue = entity.ContractType;
                txtContractStatement.Text = entity.ContractStatement;
                //txtContractPeriod.Text = entity.ContractPeriod.ToString();
                //txtGivenMaterialdesc.Text = entity.GivenMaterialdesc;
                //txtGivenMaterialCost.Text = entity.GivenMaterialCost.ToString();
                //txtCapitalCost.Text = entity.CapitalCost.ToString();
                radtxtReachTo.Value = (double)entity.ReachTo;
                radtxtRebate.Value = (double)entity.Rebate;

                if (entity.CustomerID != Guid.Empty)
                {
                    CtrtCustomerEntity userEntity = new CtrtCustomerBll().Get<CtrtCustomerEntity>(entity.CustomerID);
                    hiddenuserName.InnerText = userEntity.CustomerName;
                    hiddenUserID.Value = userEntity.CustomerID.ToString();
                }

                listContractType.Enabled = false;

                if (entity.InstanceID != Guid.Empty)
                {
                    BindWorkflow(entity.InstanceID);
                }
                if (entity.Status == (int)Enumerator.ContractStatus.Submit || entity.Status == (int)Enumerator.ContractStatus.Pass || entity.Status == (int)Enumerator.ContractStatus.Nullify)
                {
                    lnkbtnSave.Enabled = false;
                    lnkbtnSaveAndClose.Enabled = false;
                    lnkbtnSaveAndNew.Enabled = false;
                    lnkbtnSubmit.Enabled = false;
                }

                //合同变更信息
                if (entity.OriginalContractID != Guid.Empty)
                {
                    txtChangeRemark.Text = entity.ChangeRemark;
                    lnkOrginalContract.NavigateUrl = "ContractAdd.aspx?ContractID="+entity.OriginalContractID;
                }
                else
                {
                    ltlChangeTitle.Visible = false;
                    pnlChange.Visible = false;
                }
            }
            else
            {
                lnkbtnSubmit.Enabled = false;
            }
        }

        private void CheckTabPermission()
        {
            SystemBll bll = new SystemBll();

            //检查利润预算权限
            if (!bll.CheckUserHasFuction(base.CurrentUserID, 0, "ContractManage/ContractProfitSale.aspx"))
            {
                divTarget.Visible = false;
            }
            else
            { divTarget.Visible = true; }

            if (!bll.CheckUserHasFuction(base.CurrentUserID, 0, "ContractManage/ContractProfitPut.aspx"))
            {
                divTarget.Visible = false;
            }
            else
            { divTarget.Visible = true; }

            if (!bll.CheckUserHasFuction(base.CurrentUserID, 0, "ContractManage/ContractDocument.aspx"))
            {
                divDocument.Visible = false;
            }
            else
            { divDocument.Visible = true; }
        }

        protected void lnkbtnSave_Click(object sender, EventArgs e)
        {
            string Message = "";
            if (!Save(ref Message))
            {
                ClientScript.RegisterStartupScript(this.GetType(), "saveandcloseerror", "alert('" + Message + "');", true);
            }
            else
                ClientScript.RegisterStartupScript(this.GetType(), "save", "alert('保存成功');", true);
        }

        protected void lnkbtnSaveAndClose_Click(object sender, EventArgs e)
        {
            string Message = "";
            if (!Save(ref Message))
            {
                ClientScript.RegisterStartupScript(this.GetType(), "saveandssscloseerror", "alert('" + Message + "');", true);
            }
            else
                ClientScript.RegisterStartupScript(this.GetType(), "saveandclose", "window.close();", true);
        }

        protected void lnkbtnSaveAndNew_Click(object sender, EventArgs e)
        {
            string Message = "";
            if (!Save(ref Message))
            {
                ClientScript.RegisterStartupScript(this.GetType(), "saveansrror", "alert('" + Message + "');", true);
            }
            else
            {
                ContractID = Guid.Empty;
                txtContractCode.Text = "";
                txtContractApplyDate.SelectedDate = null;
                //txtContractEstimateSignDate.SelectedDate = null;
                txtContractStatement.Text = "";
                //txtContractPeriod.Text = "";
                //txtGivenMaterialdesc.Text = "";
               //txtGivenMaterialCost.Text = "";
                //txtCapitalCost.Text = "";
                ClientScript.RegisterStartupScript(this.GetType(), "saveandnew", "alert('保存成功');", true);
            }
        }

        private bool Save(ref string Message)
        {
            ContractBll bll = new ContractBll();
            CtrtContractEntity entity = new CtrtContractEntity();

            //check contract code 唯一性
            OperateResult result = bll.CheckContractCode(ContractID, txtContractCode.Text.Trim());

            if (!(bool)result.Result)
            {                
                    Message = "合同编号已存在!";
                    return false; 
            } 

            //try save info
            if (ContractID != Guid.Empty)
            {
                entity = bll.Get<CtrtContractEntity>(ContractID);
            }
            else
            {
                entity = new CtrtContractEntity();
                ContractID = entity.ContractID;
                entity.CreatedBy = CurrentUserID;
                entity.CreatedOn = DateTime.Now;
                entity.PutDiscount = 1;//默认为1
                entity.PutPaymentType = (int)Enumerator.PutPaymentType.Prepayment;

                entity.Status = (int)Enumerator.ContractStatus.Draft; 
            }

            if(hiddenUserID.Value != string.Empty)
            entity.CustomerID = new Guid(hiddenUserID.Value);
            entity.ContractCode = txtContractCode.Text;
            if(listContractAttribute.SelectedValue != string.Empty)
            entity.ContractAttribute = new Guid(listContractAttribute.SelectedValue);
            if (txtContractApplyDate.SelectedDate.HasValue)
                entity.ContractApplyDate = txtContractApplyDate.SelectedDate.Value;
            //if (txtContractEstimateSignDate.SelectedDate.HasValue)
            //    entity.ContractEstimateSignDate = txtContractEstimateSignDate.SelectedDate.Value;
            entity.ContractType = listContractType.SelectedValue;
            entity.ContractStatement = txtContractStatement.Text;
            //if(txtContractPeriod.Text != string.Empty)
            //    entity.ContractPeriod = Convert.ToInt32(txtContractPeriod.Text);
            //entity.GivenMaterialdesc = txtGivenMaterialdesc.Text;
            //if (txtGivenMaterialCost.Text != string.Empty)
            //    entity.GivenMaterialCost = Convert.ToDecimal(txtGivenMaterialCost.Text);
            //if(txtCapitalCost.Text != string.Empty)
            //    entity.CapitalCost = Convert.ToDecimal(txtCapitalCost.Text);
            if (radtxtReachTo.Value.HasValue)
                entity.ReachTo = (decimal)radtxtReachTo.Value.Value;
            if (radtxtRebate.Value.HasValue)
                entity.Rebate = (decimal)radtxtRebate.Value.Value;
            entity.ChangeRemark = txtChangeRemark.Text;

            bll.InsertOrUpdate(entity);

            txtContractID.Value = ContractID.ToString();
            listContractType.Enabled = false;

            if (entity.CustomerID != Guid.Empty)
            {
                CtrtCustomerEntity userEntity = new CtrtCustomerBll().Get<CtrtCustomerEntity>(entity.CustomerID);
                hiddenuserName.InnerText = userEntity.CustomerName;
                hiddenUserID.Value = userEntity.CustomerID.ToString();
            }
            lnkbtnSubmit.Enabled = true;
            return true;
        }

        private void LoadItem()
        {
            if (ContractID == Guid.Empty) return;

            List<SqlDbParameter> parms = new List<SqlDbParameter>();
            SqlDbParameter parm = null;
            
            parm = new SqlDbParameter();
            parm.ColumnName = "ContractID";
            parm.ColumnType = DbType.Guid;
            parm.ParameterName = "@ContractID";
            parm.ParameterValue = ContractID;
            parm.QualificationType = SqlDbParameter.QualificationSymbol.Equal;
            parms.Add(parm);

            List<CtrtContractItemEntity> list = new CtrtContractItemBll().GetAll<CtrtContractItemEntity>(parms);

            //RepeaterContractItem.DataSource = list;
            //RepeaterContractItem.DataBind();
        }

        protected void RepeaterContractItem_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "refersh")
            {
                LoadItem();
            }
        }

        protected void lnkbtnSubmit_Click(object sender, EventArgs e)
        {
            CtrtContractBll bll = new CtrtContractBll();
            CtrtContractEntity entity = bll.Get<CtrtContractEntity>(ContractID);
            if(entity == null)
            {
                ClientScript.RegisterStartupScript(this.GetType(), "Error1", "alert('系统出现错误,请联系管理员');window.close();", true);
                return;
            }

            //检查买断合同的合同明细的总金额与付款信息中的总金额相等
            if (entity.ContractType == ((int)Enumerator.ContractType.Sale).ToString())
            {
                ContractCalculateBll Calcbll = new ContractCalculateBll();
                //获取合同明细总金额
                decimal ContractItemCost = Calcbll.SumContractItemTotalPrice(ContractID);

                //合同付款明细总金额
                decimal ContractPayAmount = Calcbll.GetContractPayment(ContractID);

                if (ContractItemCost != ContractPayAmount)
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "error2", "alert('合同总金额与付款总金额不相等!');", true);
                    return;
                }
            }

            IWorkflowInstance instance = this.GetInstance(Runda.CMS.Common.Utility.DeclareHelper.ModelConstant.ModelContract);
            instance.OnNextRouting += new EventHandler<RoutingEventArgs>(instance_OnNextRouting);

            if (entity.InstanceID == Guid.Empty)
            {
                instance.Start(ContractID, "合同编号为" + entity.ContractCode);
            }
            else
            {
                instance.ReStart(entity.InstanceID);
            }
            ClientScript.RegisterStartupScript(this.GetType(), "saveandclose", "window.close();", true);
        }

        void instance_OnNextRouting(object sender, RoutingEventArgs e)
        {
            StringBuilder sb = new StringBuilder();
            if (e.RoutingEntity.NextActivityID != Guid.Empty)
            {
                List<SqlDbParameter> parms = new List<SqlDbParameter>();
                SqlDbParameter parm = null;
                parm = new SqlDbParameter();
                parm.ColumnName = "ActivityID";
                parm.ColumnType = DbType.String;
                parm.ParameterName = "@ActivityID";
                parm.ParameterValue = e.RoutingEntity.NextActivityID;
                parm.QualificationType = SqlDbParameter.QualificationSymbol.Like;
                parms.Add(parm);

                WflActivityCheckersBll wacbll = new WflActivityCheckersBll();
                List<WflActivityCheckersEntity> list = wacbll.GetAll<WflActivityCheckersEntity>(parms);

                foreach (WflActivityCheckersEntity c in list)
                {
                    sb.Append(c.UserName).Append("(").Append(c.Account).Append(")").Append(",");

                    SysUserEntity userEntity = new SysUserBll().Get<SysUserEntity>(c.UserID);
                    //发送邮件给审核人
                    MailHandle.SendEmailNotice(base.CurrentUserEntity.UserName, userEntity.Email, "一份合同需要您的审核，合同编号：" + txtContractCode.Text.ToString() + "");
                }
            }
            CtrtContractBll bll = new CtrtContractBll();
            CtrtContractEntity entity = bll.Get<CtrtContractEntity>(ContractID);
            entity.InstanceID = e.InstanceID;
            entity.NextCheckers = sb.ToString().TrimEnd(',');
            entity.Status = (int)Enumerator.ContractStatus.Submit;
            bll.Update(entity);
        }

        public string GetStatusText(int status)
        {
            string text = string.Empty;
            EnumeratorHelper[] cs = EnumeratorHelper.GetFieldTexts(typeof(Runda.CMS.Workflow.ActivityStatus));
            foreach (EnumeratorHelper c in cs)
            {
                if (c.EnumValue == status)
                {
                    text = c.EnumDisplayText; break;
                }
            }

            return text;
        }

        private void BindWorkflow(Guid InstanceID)
        {
            List<WflInstanceRoutingEntity> list = new WflInstanceRoutingBll().GetAll<WflInstanceRoutingEntity>(" and InstanceID = '" + InstanceID + "' and CheckStatus != 1 order by CheckDate");

            RepeaterApprove.DataSource = list;
            RepeaterApprove.DataBind();
        }        
    }
}
